import React, { useEffect, useRef, useState } from 'react';
import {
  Card,
  Button,
  Space,
  Tag,
  Modal,
  Descriptions,
  Empty,
  Spin,
  Input,
  Select,
  Row,
  Col,
  Tooltip,
  Switch,
  Slider,
  Divider,
  Typography,
  theme
} from 'antd';
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  ExpandOutlined,
  InfoCircleOutlined,
  ArrowLeftOutlined,
  SearchOutlined,
  FilterOutlined,
  AppstoreOutlined,
  NodeIndexOutlined,
  RadarChartOutlined,
  BorderOutlined,
  DragOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined
} from '@ant-design/icons';
import cytoscape from 'cytoscape';
import dagre from 'cytoscape-dagre';
import coseBilkent from 'cytoscape-cose-bilkent';
import fcose from 'cytoscape-fcose';
import { getLineageThemeConfig, getTaskLevelCytoscapeStyles, getCytoscapeStyles } from '../utils/lineageTheme';

// 注册布局扩展
cytoscape.use(dagre);
cytoscape.use(coseBilkent);
cytoscape.use(fcose);

interface TaskNode {
  id: string;
  label: string;
  type: 'task';
  task_id: number;
  task_name: string;
  node_count: number;
  edge_count: number;
  source_tables: string[];
  target_tables: string[];
  internal_nodes: any[];
  internal_edges: any[];
}

interface TaskEdge {
  source: string;
  target: string;
  type: 'task_dependency';
  dependency_type?: string;
  common_tables: string[];
  connector_key?: string;
  connector_type?: string;
  connector_id?: string;
  source_task_name: string;
  target_task_name: string;
}

interface LineageGraphData {
  task_level_nodes?: TaskNode[];
  task_level_edges?: TaskEdge[];
  task_lineage_results?: any[];
  nodes: any[];
  edges: any[];
  connectors: string[];
}

interface HierarchicalLineageGraphProps {
  data: LineageGraphData | null;
  loading?: boolean;
}

// 自定义比较函数，只有data内容真正变化时才重新渲染
const arePropsEqual = (prevProps: HierarchicalLineageGraphProps, nextProps: HierarchicalLineageGraphProps) => {
  // 如果loading状态变化，需要重新渲染
  if (prevProps.loading !== nextProps.loading) {
    return false;
  }

  // 如果data引用相同，不需要重新渲染
  if (prevProps.data === nextProps.data) {
    return true;
  }

  // 如果一个为null另一个不为null，需要重新渲染
  if ((prevProps.data === null) !== (nextProps.data === null)) {
    return false;
  }

  // 如果都为null，不需要重新渲染
  if (prevProps.data === null && nextProps.data === null) {
    return true;
  }

  // 深度比较data内容
  const prev = prevProps.data!;
  const next = nextProps.data!;

  // 比较关键数据字段
  const prevTaskNodes = prev.task_level_nodes?.length || 0;
  const nextTaskNodes = next.task_level_nodes?.length || 0;
  const prevTaskEdges = prev.task_level_edges?.length || 0;
  const nextTaskEdges = next.task_level_edges?.length || 0;
  const prevNodes = prev.nodes?.length || 0;
  const nextNodes = next.nodes?.length || 0;
  const prevEdges = prev.edges?.length || 0;
  const nextEdges = next.edges?.length || 0;

  return (
    prevTaskNodes === nextTaskNodes &&
    prevTaskEdges === nextTaskEdges &&
    prevNodes === nextNodes &&
    prevEdges === nextEdges &&
    JSON.stringify(prev.connectors) === JSON.stringify(next.connectors)
  );
};

const HierarchicalLineageGraphComponent: React.FC<HierarchicalLineageGraphProps> = ({ data, loading }) => {
  const { token } = theme.useToken();
  const themeConfig = getLineageThemeConfig(token);
  const [currentView, setCurrentView] = useState<'task' | 'detail'>('task');
  const [selectedTask, setSelectedTask] = useState<TaskNode | null>(null);
  const [taskDetailVisible, setTaskDetailVisible] = useState(false);
  const [selectedNode, setSelectedNode] = useState<any>(null);
  const [nodeDetailVisible, setNodeDetailVisible] = useState(false);
  const [sidebarVisible, setSidebarVisible] = useState(false);

  // 新增状态
  const [searchText, setSearchText] = useState('');
  const [selectedLayout, setSelectedLayout] = useState<string>('cose');
  const [filterConnector, setFilterConnector] = useState<string>('all');
  const [showMinimap, setShowMinimap] = useState(false);
  const [nodeSize, setNodeSize] = useState(200);
  const [filteredNodes, setFilteredNodes] = useState<TaskNode[]>([]);
  const [filteredEdges, setFilteredEdges] = useState<TaskEdge[]>([]);
  const [isDraggable, setIsDraggable] = useState(true); // 默认启用拖拽
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [currentStats, setCurrentStats] = useState({
    displayedTasks: 0,
    displayedConnections: 0,
    totalTasks: 0,
    totalConnections: 0
  });
  
  const taskCyRef = useRef<cytoscape.Core | null>(null);
  const detailCyRef = useRef<cytoscape.Core | null>(null);
  const taskContainerRef = useRef<HTMLDivElement>(null);
  const detailContainerRef = useRef<HTMLDivElement>(null);

  // 计算当前显示的统计信息
  const calculateCurrentStats = () => {
    const totalTasks = data?.task_level_nodes?.length || 0;
    const totalConnections = data?.task_level_edges?.length || 0;
    const displayedTasks = filteredNodes.length || totalTasks;
    const displayedConnections = filteredEdges.length || totalConnections;

    return {
      displayedTasks,
      displayedConnections,
      totalTasks,
      totalConnections
    };
  };

  // 数据一致性验证函数
  const validateDataConsistency = () => {
    if (!data) return;

    console.group('🔍 数据一致性检查');

    // 检查任务级数据
    const taskLevelNodes = data.task_level_nodes || [];
    const taskLevelEdges = data.task_level_edges || [];
    const allNodes = data.nodes || [];
    const allEdges = data.edges || [];
    const connectors = data.connectors || [];
    const statistics = data.statistics || {};




    // 检查不一致性
    const inconsistencies = [];
    if (statistics.task_level_nodes && statistics.task_level_nodes !== taskLevelNodes.length) {
      inconsistencies.push(`任务节点数不一致: 统计${statistics.task_level_nodes} vs 实际${taskLevelNodes.length}`);
    }
    if (statistics.task_level_edges && statistics.task_level_edges !== taskLevelEdges.length) {
      inconsistencies.push(`任务连接数不一致: 统计${statistics.task_level_edges} vs 实际${taskLevelEdges.length}`);
    }
    if (statistics.total_nodes && statistics.total_nodes !== allNodes.length) {
      inconsistencies.push(`节点总数不一致: 统计${statistics.total_nodes} vs 实际${allNodes.length}`);
    }
    if (statistics.total_edges && statistics.total_edges !== allEdges.length) {
      inconsistencies.push(`连接总数不一致: 统计${statistics.total_edges} vs 实际${allEdges.length}`);
    }
    if (statistics.total_connectors && statistics.total_connectors !== connectors.length) {
      inconsistencies.push(`连接器数不一致: 统计${statistics.total_connectors} vs 实际${connectors.length}`);
    }

    if (inconsistencies.length > 0) {
      console.warn('⚠️ 发现数据不一致:');
      inconsistencies.forEach(issue => console.warn('  -', issue));
    } else {
      console.log('✅ 数据一致性检查通过');
    }

    console.groupEnd();
  };

  // 检查连接器类型是否匹配分组
  const matchesConnectorGroup = (connectorType: string | undefined | null, filterGroup: string): boolean => {
    if (filterGroup === 'all') return true;

    // 添加空值检查
    if (!connectorType || typeof connectorType !== 'string') {
      return filterGroup === 'other'; // 未知类型归类为其他
    }

    const lowerType = connectorType.toLowerCase();
    switch (filterGroup) {
      case 'kafka':
        return lowerType.includes('kafka') || lowerType.includes('upsert');
      case 'doris':
        return lowerType.includes('doris');
      case 'mysql':
        return lowerType.includes('mysql');
      case 'hbase':
        return lowerType.includes('hbase');
      case 'pulsar':
        return lowerType.includes('pulsar');
      case 'sqlserver':
        return lowerType.includes('sqlserver') || lowerType.includes('cdc');
      case 'oracle':
        return lowerType.includes('oracle');
      case 'other':
        return !['kafka', 'doris', 'mysql', 'hbase', 'pulsar', 'sqlserver', 'oracle', 'upsert', 'cdc'].some(keyword =>
          lowerType.includes(keyword)
        );
      default:
        return lowerType.includes(filterGroup);
    }
  };

  // 过滤和搜索逻辑
  const filterAndSearchTasks = () => {
    if (!data?.task_level_nodes) return;

    // 连接器类型过滤
    let filteredEdges = data.task_level_edges || [];
    if (filterConnector !== 'all') {
      filteredEdges = filteredEdges.filter(edge => {
        // 确保edge对象存在且有必要的属性
        if (!edge || typeof edge !== 'object') return false;
        return matchesConnectorGroup(edge.dependency_type, filterConnector);
      });

      // 只保留有相关连接的任务
      const connectedTaskIds = new Set();
      filteredEdges.forEach(edge => {
        connectedTaskIds.add(edge.source);
        connectedTaskIds.add(edge.target);
      });

      if (connectedTaskIds.size > 0) {
        const filtered = data.task_level_nodes.filter(task => connectedTaskIds.has(task.id));
        setFilteredNodes(filtered);
      } else {
        setFilteredNodes(data.task_level_nodes);
      }
    } else {
      setFilteredNodes(data.task_level_nodes);
    }

    setFilteredEdges(filteredEdges);

    // 更新统计信息
    setCurrentStats(calculateCurrentStats());
  };

  // 搜索高亮功能
  const highlightSearchResults = () => {
    if (!taskCyRef.current || !searchText || typeof searchText !== 'string') {
      // 清除所有高亮
      taskCyRef.current?.elements().removeClass('search-highlighted search-dimmed');
      return;
    }

    const searchLower = searchText.toLowerCase();
    const matchedNodes = taskCyRef.current.nodes().filter((node: any) => {
      const taskName = node.data('label') || '';
      const taskId = node.data('id') || '';
      return taskName.toLowerCase().includes(searchLower) ||
             taskId.toLowerCase().includes(searchLower);
    });

    // 清除之前的搜索高亮
    taskCyRef.current.elements().removeClass('search-highlighted search-dimmed');

    if (matchedNodes.length > 0) {
      // 高亮匹配的节点
      matchedNodes.addClass('search-highlighted');
      // 淡化其他节点
      taskCyRef.current.elements().not(matchedNodes).addClass('search-dimmed');

      // 自动聚焦到匹配的节点
      taskCyRef.current.fit(matchedNodes, 100);
    }
  };



  // 获取布局配置
  const getLayoutConfig = (layoutName: string, nodeCount: number) => {
    const baseConfig = {
      animate: true,
      animationDuration: 1000,
      fit: true,
      padding: 80
    };

    switch (layoutName) {
      case 'cose':
        return {
          ...baseConfig,
          name: 'cose-bilkent',
          idealEdgeLength: 200,
          nodeOverlap: 20,
          refresh: 20,
          randomize: false,
          componentSpacing: 150,
          nodeRepulsion: 4500,
          edgeElasticity: 0.45,
          nestingFactor: 0.1,
          gravity: 0.25,
          numIter: 2500,
          tile: true,
          tilingPaddingVertical: 10,
          tilingPaddingHorizontal: 10
        };
      case 'fcose':
        return {
          ...baseConfig,
          name: 'fcose',
          quality: 'default',
          randomize: false,
          animate: 'end',
          animationDuration: 1000,
          animationEasing: undefined,
          fit: true,
          padding: 100,
          nodeDimensionsIncludeLabels: false,
          uniformNodeDimensions: false,
          packComponents: true,
          nodeRepulsion: 4500,
          idealEdgeLength: 50,
          edgeElasticity: 0.45,
          nestingFactor: 0.1,
          gravity: 0.25,
          numIter: 2500,
          tile: true,
          tilingCompareBy: undefined,
          tilingPaddingVertical: 10,
          tilingPaddingHorizontal: 10,
          gravityRangeCompound: 1.5,
          gravityCompound: 1.0,
          gravityRange: 3.8,
          initialEnergyOnIncremental: 0.3
        };
      case 'dagre':
        return {
          ...baseConfig,
          name: 'dagre',
          directed: true,
          padding: 100,
          spacingFactor: 1.75,
          rankDir: 'TB',
          ranker: 'network-simplex'
        };
      case 'grid':
        return {
          ...baseConfig,
          name: 'grid',
          padding: 100,
          spacingFactor: 2,
          avoidOverlap: true,
          condense: false
        };
      case 'circle':
        return {
          ...baseConfig,
          name: 'circle',
          padding: 100,
          spacingFactor: 2,
          radius: Math.max(300, nodeCount * 30)
        };
      case 'concentric':
        return {
          ...baseConfig,
          name: 'concentric',
          padding: 100,
          spacingFactor: 2,
          concentric: (node: any) => node.data('importance') || 1,
          levelWidth: () => 2,
          minNodeSpacing: 100
        };
      default:
        return {
          ...baseConfig,
          name: 'breadthfirst',
          directed: true,
          padding: 100,
          spacingFactor: 2.5
        };
    }
  };

  // 创建任务级别的血缘图
  const createTaskLevelGraph = () => {
    if (!taskContainerRef.current) return;

    // 安全获取数据，添加类型检查和默认值
    const nodesToUse = filteredNodes.length > 0 ? filteredNodes : (data?.task_level_nodes || []);
    const edgesToUse = filteredEdges.length > 0 ? filteredEdges : (data?.task_level_edges || []);

    // 验证数据有效性
    if (!Array.isArray(nodesToUse) || nodesToUse.length === 0) {
      console.warn('任务级节点数据无效或为空:', nodesToUse);
      return;
    }

    if (!Array.isArray(edgesToUse)) {
      console.warn('任务级边数据无效:', edgesToUse);
      return;
    }



    // 清理现有实例
    if (taskCyRef.current) {
      taskCyRef.current.destroy();
    }

    // 转换任务节点 - 根据重要性调整大小，添加数据验证
    const cytoscapeNodes = nodesToUse.map((task, index) => {
      // 数据验证和默认值处理
      const taskId = task.id || `task_${index}`;
      const taskName = task.task_name || task.label || `Task ${index + 1}`;
      const nodeCount = typeof task.node_count === 'number' ? task.node_count : 0;
      const edgeCount = typeof task.edge_count === 'number' ? task.edge_count : 0;
      const sourceTables = Array.isArray(task.source_tables) ? task.source_tables : [];
      const targetTables = Array.isArray(task.target_tables) ? task.target_tables : [];

      const importance = (nodeCount + edgeCount) / 2;
      const sizeMultiplier = Math.max(0.8, Math.min(1.5, importance / 10));

      return {
        data: {
          id: taskId,
          label: taskName,
          type: 'task',
          task_id: task.task_id || index,
          node_count: nodeCount,
          edge_count: edgeCount,
          source_tables: sourceTables,
          target_tables: targetTables,
          size_multiplier: sizeMultiplier,
          importance: importance
        }
      };
    });

    // 创建节点ID集合用于验证边的有效性
    const nodeIdSet = new Set(cytoscapeNodes.map(node => node.data.id));

    // 转换任务边，添加数据验证和节点存在性检查
    const validEdges = edgesToUse.filter(edge => {
      // 基本数据验证
      if (!edge || !edge.source || !edge.target) {
        console.warn('跳过无效边数据:', edge);
        return false;
      }

      // 检查源节点是否存在
      if (!nodeIdSet.has(edge.source)) {
        console.warn(`跳过边：源节点 '${edge.source}' 不存在于节点列表中`);
        return false;
      }

      // 检查目标节点是否存在
      if (!nodeIdSet.has(edge.target)) {
        console.warn(`跳过边：目标节点 '${edge.target}' 不存在于节点列表中`);
        return false;
      }

      return true;
    });


    const cytoscapeEdges = validEdges.map((edge, index) => {
      let label = '';
      let edgeColor = '#52c41a';

      // 根据连接器类型设置颜色和标签
      const connectorColors = {
        'kafka_topic': '#fa8c16',         // 橙色 - Kafka
        'upsert_kafka_topic': '#d46b08',  // 深橙色 - Upsert Kafka
        'sqlserver_cdc_table': '#096dd9', // 深蓝色 - SQL Server CDC
        'pulsar_topic': '#722ed1',        // 紫色 - Pulsar
        'redis_key': '#f5222d',           // 红色 - Redis
        'elasticsearch_index': '#13c2c2', // 青色 - Elasticsearch
        'hbase_table': '#faad14',         // 黄色 - HBase
        'mongodb_collection': '#52c41a',  // 绿色 - MongoDB
        'hdfs_path': '#1890ff',           // 蓝色 - HDFS
        's3_path': '#eb2f96',             // 粉色 - S3
        'shared_table': '#52c41a'         // 绿色 - 共享表
      };

      if (edge.dependency_type && edge.dependency_type !== 'shared_table') {
        const displayType = edge.dependency_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
        label = `${displayType}: ${edge.connector_id || 'unknown'}`;
        edgeColor = connectorColors[edge.dependency_type] || '#666666';
      } else {
        // 安全处理 common_tables 数组，防止 undefined 错误
        const commonTables = edge.common_tables || [];
        label = `共享表: ${Array.isArray(commonTables) ? commonTables.join(', ') : 'unknown'}`;
        edgeColor = connectorColors['shared_table'];
      }

      return {
        data: {
          id: `task_edge_${index}`,
          source: edge.source,
          target: edge.target,
          type: 'task_dependency',
          dependency_type: edge.dependency_type || 'shared_table',
          common_tables: edge.common_tables,
          connector_key: edge.connector_key,
          connector_type: edge.connector_type,
          connector_id: edge.connector_id,
          label: label,
          edge_color: edgeColor
        }
      };
    });

    try {
      // 最终验证：确保所有边的源节点和目标节点都存在
      const finalValidation = cytoscapeEdges.every(edge => {
        const sourceExists = cytoscapeNodes.some(node => node.data.id === edge.data.source);
        const targetExists = cytoscapeNodes.some(node => node.data.id === edge.data.target);

        if (!sourceExists) {
          console.error(`致命错误：边 ${edge.data.id} 的源节点 ${edge.data.source} 不存在`);
          return false;
        }

        if (!targetExists) {
          console.error(`致命错误：边 ${edge.data.id} 的目标节点 ${edge.data.target} 不存在`);
          return false;
        }

        return true;
      });

      if (!finalValidation) {
        console.error('数据一致性验证失败，无法创建图表');
        return;
      }


      taskCyRef.current = cytoscape({
        container: taskContainerRef.current,
        elements: [...cytoscapeNodes, ...cytoscapeEdges],
        userZoomingEnabled: true,
        userPanningEnabled: true,
        boxSelectionEnabled: false,
        autoungrabify: !isDraggable, // 根据状态控制是否可拖拽
        style: getTaskLevelCytoscapeStyles(themeConfig, nodeSize),
        layout: getLayoutConfig(selectedLayout, nodesToUse.length)
      });

      // 单击节点高亮相关任务
      taskCyRef.current.on('tap', 'node[type="task"]', (event) => {
        const node = event.target;
        const connectedEdges = node.connectedEdges();
        const connectedNodes = connectedEdges.connectedNodes();

        // 清除搜索高亮，应用交互高亮
        taskCyRef.current?.elements().removeClass('highlighted dimmed search-highlighted search-dimmed');
        node.addClass('highlighted');
        connectedNodes.addClass('highlighted');
        connectedEdges.addClass('highlighted');
        taskCyRef.current?.elements().not(node.union(connectedNodes).union(connectedEdges)).addClass('dimmed');
      });

      // 双击节点进入详情
      taskCyRef.current.on('dblclick', 'node[type="task"]', (event) => {
        const nodeData = event.target.data();
        const taskNode = data.task_level_nodes?.find(t => t.id === nodeData.id);

        if (taskNode) {
          setSelectedTask(taskNode);
          setTaskDetailVisible(true);
        }
      });

      // 点击空白区域清除高亮
      taskCyRef.current.on('tap', (event) => {
        if (event.target === taskCyRef.current) {
          taskCyRef.current?.elements().removeClass('highlighted dimmed');
          // 如果有搜索文本，重新应用搜索高亮
          if (searchText) {
            highlightSearchResults();
          }
        }
      });


    } catch (error) {
      console.error('创建任务级血缘图失败:', error);
    }
  };

  // 创建任务详情血缘图
  const createTaskDetailGraph = (taskNode: TaskNode) => {
    if (!detailContainerRef.current) return;

    // 验证任务节点数据
    if (!taskNode || !Array.isArray(taskNode.internal_nodes)) {
      console.warn('任务详情数据无效:', taskNode);
      return;
    }

    // 清理现有实例
    if (detailCyRef.current) {
      detailCyRef.current.destroy();
    }

    // 节点颜色配置
    const nodeColors = {
      source_table: '#1890ff',
      target_table: '#52c41a', 
      temp_table: '#faad14',
      view: '#722ed1'
    };

    // 转换内部节点，添加数据验证
    const cytoscapeNodes = taskNode.internal_nodes.filter(node => {
      // 过滤掉无效的节点数据
      return node && node.id && node.label;
    }).map((node, index) => ({
      data: {
        id: node.id || `internal_node_${index}`,
        label: node.label || `Node ${index + 1}`,
        type: node.type || 'unknown_table',
        color: nodeColors[node.type as keyof typeof nodeColors] || '#666666'
      }
    }));

    // 转换内部边，添加数据验证
    const internalEdges = Array.isArray(taskNode.internal_edges) ? taskNode.internal_edges : [];
    const cytoscapeEdges = internalEdges.filter(edge => {
      // 过滤掉无效的边数据
      return edge && edge.source && edge.target;
    }).map((edge, index) => ({
      data: {
        id: `detail_edge_${index}`,
        source: edge.source,
        target: edge.target,
        type: edge.type || 'data_transformation',
        label: edge.type === 'data_transformation' ? '数据转换' : (edge.type || '数据转换')
      }
    }));

    try {
      detailCyRef.current = cytoscape({
        container: detailContainerRef.current,
        elements: [...cytoscapeNodes, ...cytoscapeEdges],
        userZoomingEnabled: true,
        userPanningEnabled: true,
        boxSelectionEnabled: false,
        autoungrabify: false, // 详情视图默认启用拖拽
        style: getCytoscapeStyles(themeConfig, 80),
        layout: {
          name: 'breadthfirst',
          directed: true,
          padding: 60,
          spacingFactor: 2,
          animate: true,
          animationDuration: 800,
          fit: true
        }
      });

      // 单击节点高亮并显示侧边栏详情
      detailCyRef.current.on('tap', 'node', (event) => {
        const node = event.target;
        const nodeData = node.data();
        const fullNodeData = taskNode.internal_nodes.find(n => n.id === nodeData.id);

        // 高亮相关节点
        const connectedEdges = node.connectedEdges();
        const connectedNodes = connectedEdges.connectedNodes();

        detailCyRef.current?.elements().removeClass('highlighted dimmed');
        node.addClass('highlighted');
        connectedNodes.addClass('highlighted');
        connectedEdges.addClass('highlighted');
        detailCyRef.current?.elements().not(node.union(connectedNodes).union(connectedEdges)).addClass('dimmed');

        // 显示侧边栏详情
        if (fullNodeData) {
          setSelectedNode(fullNodeData);
          setSidebarVisible(true);
        }
      });

      // 点击空白区域清除高亮和侧边栏
      detailCyRef.current.on('tap', (event) => {
        if (event.target === detailCyRef.current) {
          detailCyRef.current?.elements().removeClass('highlighted dimmed');
          setSidebarVisible(false);
          setSelectedNode(null);
        }
      });

      console.log(`任务 ${taskNode.task_name} 的详情血缘图创建成功`);

    } catch (error) {
      console.error('创建任务详情血缘图失败:', error);
    }
  };

  // 过滤效果
  useEffect(() => {
    filterAndSearchTasks();
  }, [data, filterConnector]);

  // 初始化和更新统计信息
  useEffect(() => {
    setCurrentStats(calculateCurrentStats());

  }, [data, filteredNodes, filteredEdges]);

  // 搜索高亮效果
  useEffect(() => {
    if (taskCyRef.current) {
      highlightSearchResults();
    }
  }, [searchText]);

  // 初始化任务级血缘图 - 优化依赖项，只在数据真正变化时重新创建
  useEffect(() => {
    if (data?.task_level_nodes) {
      setTimeout(() => {
        createTaskLevelGraph();
      }, 100);
    }
  }, [data?.task_level_nodes, data?.task_level_edges, selectedLayout, nodeSize, isDraggable]);

  // 当选择任务时创建详情图
  useEffect(() => {
    if (selectedTask && taskDetailVisible) {
      setTimeout(() => {
        createTaskDetailGraph(selectedTask);
      }, 100);
    }
  }, [selectedTask, taskDetailVisible]);



  const handleResetZoom = () => {
    const cy = currentView === 'task' ? taskCyRef.current : detailCyRef.current;
    if (cy) cy.fit();
  };

  // 全屏功能
  const handleFullscreen = () => {
    const element = currentView === 'task' ? taskContainerRef.current?.parentElement : detailContainerRef.current?.parentElement;
    if (!document.fullscreenElement && element) {
      element.requestFullscreen().then(() => {
        setIsFullscreen(true);
      }).catch((err) => {
        console.error('进入全屏失败:', err);
      });
    } else {
      document.exitFullscreen().then(() => {
        setIsFullscreen(false);
      }).catch((err) => {
        console.error('退出全屏失败:', err);
      });
    }
  };

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  if (loading) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>正在解析数据库并生成血缘图...</div>
        </div>
      </Card>
    );
  }

  if (!data || !data.task_level_nodes || data.task_level_nodes.length === 0) {
    return (
      <Card>
        <Empty 
          description="暂无任务级血缘图数据"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </Card>
    );
  }

  return (
    <>
      <Card
        title={
          <Space>
            <span>{`任务级数据血缘图`}</span>
            <Tag color="blue">总任务: {currentStats.totalTasks}</Tag>
            <Tag color="green">总连接: {currentStats.totalConnections}</Tag>
            {(currentStats.displayedTasks !== currentStats.totalTasks ||
              currentStats.displayedConnections !== currentStats.totalConnections) && (
              <Tag color="orange">
                显示: {currentStats.displayedTasks}任务 / {currentStats.displayedConnections}连接
              </Tag>
            )}
          </Space>
        }
      >
        {/* 控制面板 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          {/* 搜索框 */}
          <Col xs={24} sm={12} md={8} lg={6} xl={6}>
            <Input
              placeholder="搜索任务名称..."
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
            />
          </Col>

          {/* 布局选择 */}
          <Col xs={12} sm={6} md={4} lg={4} xl={4}>
            <Select
              placeholder="选择布局"
              value={selectedLayout}
              onChange={setSelectedLayout}
              style={{ width: '100%' }}
              options={[
                { value: 'cose', label: '智能力导向', icon: <RadarChartOutlined /> },
                { value: 'fcose', label: '快速力导向', icon: <RadarChartOutlined /> },
                { value: 'dagre', label: '层次布局', icon: <NodeIndexOutlined /> },
                { value: 'grid', label: '网格布局', icon: <AppstoreOutlined /> },
                { value: 'circle', label: '圆形布局', icon: <BorderOutlined /> },
                { value: 'concentric', label: '同心圆布局', icon: <RadarChartOutlined /> },
                { value: 'breadthfirst', label: '广度优先', icon: <NodeIndexOutlined /> }
              ]}
            />
          </Col>

          {/* 连接器过滤 */}
          <Col xs={12} sm={6} md={4} lg={4} xl={4}>
            <Select
              placeholder="连接器过滤"
              value={filterConnector}
              onChange={setFilterConnector}
              style={{ width: '100%' }}
              showSearch
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={[
                { value: 'all', label: '🔗 全部连接器' },
                { value: 'kafka', label: '📨 Kafka相关', group: 'kafka' },
                { value: 'doris', label: '🗄️ Doris相关', group: 'doris' },
                { value: 'mysql', label: '🐬 MySQL相关', group: 'mysql' },
                { value: 'hbase', label: '📊 HBase相关', group: 'hbase' },
                { value: 'pulsar', label: '🚀 Pulsar相关', group: 'pulsar' },
                { value: 'sqlserver', label: '🏢 SQL Server相关', group: 'sqlserver' },
                { value: 'oracle', label: '🔶 Oracle相关', group: 'oracle' },
                { value: 'other', label: '🔧 其他连接器', group: 'other' }
              ]}
            />
          </Col>

          {/* 节点大小控制 */}
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
            <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap' }}>
              <span style={{ marginRight: 8, whiteSpace: 'nowrap' }}>节点大小:</span>
              <Slider
                min={100}
                max={300}
                value={nodeSize}
                onChange={setNodeSize}
                style={{ flex: 1, minWidth: 80 }}
              />
            </div>
          </Col>

          {/* 操作按钮组 */}
          <Col xs={24} sm={24} md={24} lg={24} xl={6}>
            <Space wrap size="small" style={{ width: '100%', justifyContent: 'flex-end' }}>

              <Button icon={<ReloadOutlined />} onClick={handleResetZoom} size="small">
                适应窗口
              </Button>
              <Button
                icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                onClick={handleFullscreen}
                size="small"
              >
                {isFullscreen ? '退出全屏' : '全屏'}
              </Button>
              <Tooltip title={isDraggable ? "禁用拖拽" : "启用拖拽"}>
                <Switch
                  checked={isDraggable}
                  checkedChildren={<DragOutlined />}
                  unCheckedChildren={<DragOutlined />}
                  onChange={(checked) => {
                    setIsDraggable(checked);
                    if (taskCyRef.current) {
                      taskCyRef.current.autoungrabify(!checked);
                    }
                  }}
                />
              </Tooltip>
            </Space>
          </Col>
        </Row>
        {/* 图表容器 */}
        <div style={{ position: 'relative' }}>
          <div
            ref={taskContainerRef}
            style={{
              width: '100%',
              height: isFullscreen ? '100vh' : '700px',
              border: `2px solid ${token.colorBorder}`,
              borderRadius: '8px',
              backgroundColor: token.colorBgContainer
            }}
          />

          {/* 统计信息悬浮框 */}
          <div style={{
            position: 'absolute',
            top: 10,
            right: 10,
            background: token.colorInfoBg || token.colorFillQuaternary,
            padding: '8px 12px',
            borderRadius: '6px',
            border: '1px solid #d9d9d9',
            fontSize: '12px',
            minWidth: '160px'
          }}>
            <div>
              <strong>当前显示:</strong>
            </div>
            <div>任务: {currentStats.displayedTasks} / {currentStats.totalTasks}</div>
            <div>连接: {currentStats.displayedConnections} / {currentStats.totalConnections}</div>
            <div>布局: {selectedLayout}</div>
            {(currentStats.displayedTasks !== currentStats.totalTasks ||
              currentStats.displayedConnections !== currentStats.totalConnections) && (
              <div style={{ color: '#faad14', marginTop: '4px' }}>
                <small>已应用过滤</small>
              </div>
            )}
          </div>
        </div>
        
        <div style={{
          marginTop: '16px',
          padding: '16px',
          backgroundColor: token.colorInfoBg || token.colorFillQuaternary,
          borderRadius: '8px',
          border: `1px solid ${token.colorInfoBorder || token.colorBorder}`
        }}>
          <h4 style={{ color: token.colorPrimary, marginBottom: '8px' }}>
            <InfoCircleOutlined style={{ marginRight: 8 }} />
            使用说明
          </h4>
          <div style={{ fontSize: '14px', color: token.colorTextSecondary }}>
            • 每个方框代表一个 dinky_task 任务，颜色表示重要性：<br/>
            &nbsp;&nbsp;- <span style={{color: '#1890ff'}}>蓝色</span>: 普通任务<br/>
            &nbsp;&nbsp;- <span style={{color: '#fa8c16'}}>橙色</span>: 中等重要性任务<br/>
            &nbsp;&nbsp;- <span style={{color: '#ff4d4f'}}>红色</span>: 高重要性任务<br/>
            • 不同颜色的箭头表示不同类型的数据依赖关系：<br/>
            &nbsp;&nbsp;- <span style={{color: '#52c41a'}}>绿色</span>: 共享表/MongoDB<br/>
            &nbsp;&nbsp;- <span style={{color: '#fa8c16'}}>橙色</span>: Kafka Topic<br/>
            &nbsp;&nbsp;- <span style={{color: '#d46b08'}}>深橙色</span>: Upsert Kafka<br/>
            &nbsp;&nbsp;- <span style={{color: '#096dd9'}}>深蓝色</span>: SQL Server CDC<br/>
            &nbsp;&nbsp;- <span style={{color: '#722ed1'}}>紫色</span>: Pulsar Topic<br/>
            • <strong>搜索功能</strong>: 输入任务名称进行模糊搜索，匹配的任务会高亮显示<br/>
            • <strong>单击任务</strong>: 高亮显示该任务及其相关的依赖关系<br/>
            • <strong>双击任务</strong>: 查看该任务内部的表级血缘关系<br/>
            • <strong>点击空白</strong>: 清除高亮效果<br/>
            • 箭头上的标签显示具体的连接器名称或共享表名
          </div>
        </div>
      </Card>

      {/* 任务详情弹窗 */}
      <Modal
        title={
          <Space>
            <ArrowLeftOutlined />
            任务详情: {selectedTask?.task_name}
          </Space>
        }
        open={taskDetailVisible}
        onCancel={() => setTaskDetailVisible(false)}
        width="95%"
        footer={[
          <Button key="close" onClick={() => setTaskDetailVisible(false)}>
            关闭
          </Button>
        ]}
        style={{ top: 10 }}
        styles={{ body: { height: 'calc(100vh - 120px)', overflow: 'hidden' } }}
      >
        {selectedTask && (
          <>
            <Descriptions column={2} size="small" style={{ marginBottom: 16 }}>
              <Descriptions.Item label="任务ID">{selectedTask.task_id}</Descriptions.Item>
              <Descriptions.Item label="任务名称">{selectedTask.task_name}</Descriptions.Item>
              <Descriptions.Item label="节点数量">{selectedTask.node_count}</Descriptions.Item>
              <Descriptions.Item label="连接数量">{selectedTask.edge_count}</Descriptions.Item>
              <Descriptions.Item label="输入表">
                <div>
                  {selectedTask.source_tables.map(table => (
                    <Tag key={table} color="blue" style={{ marginBottom: 4 }}>{table}</Tag>
                  ))}
                </div>
              </Descriptions.Item>
              <Descriptions.Item label="输出表">
                <div>
                  {selectedTask.target_tables.map(table => (
                    <Tag key={table} color="green" style={{ marginBottom: 4 }}>{table}</Tag>
                  ))}
                </div>
              </Descriptions.Item>
            </Descriptions>

            {/* 详情视图控制按钮 */}
            <Row style={{ marginBottom: 16 }}>
              <Col span={24}>
                <Space wrap size="small" style={{ width: '100%', justifyContent: 'flex-start' }}>

                  <Button icon={<ReloadOutlined />} onClick={handleResetZoom} size="small">
                    适应窗口
                  </Button>
                  <Button
                    icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                    onClick={handleFullscreen}
                    size="small"
                  >
                    {isFullscreen ? '退出全屏' : '全屏'}
                  </Button>
                </Space>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={sidebarVisible ? 16 : 24}>
                <div
                  ref={detailContainerRef}
                  style={{
                    width: '100%',
                    height: 'calc(100vh - 300px)',
                    border: `2px solid ${token.colorBorder}`,
                    borderRadius: '8px',
                    backgroundColor: token.colorBgContainer
                  }}
                />
              </Col>

              {sidebarVisible && (
                <Col span={8}>
                  <Card
                    title={
                      <Space>
                        <InfoCircleOutlined />
                        节点详情
                        <Button
                          type="text"
                          size="small"
                          icon={<span>×</span>}
                          onClick={() => {
                            setSidebarVisible(false);
                            setSelectedNode(null);
                            if (detailCyRef.current) {
                              detailCyRef.current.elements().removeClass('highlighted dimmed');
                            }
                          }}
                          style={{ marginLeft: 'auto' }}
                        />
                      </Space>
                    }
                    size="small"
                    style={{
                      height: 'calc(100vh - 300px)',
                      overflow: 'auto',
                      border: `1px solid ${token.colorBorder}`
                    }}
                    styles={{ body: { padding: '12px', height: 'calc(100% - 57px)', overflow: 'auto' } }}
                  >
                    {selectedNode && (
                      <>
                        <Descriptions column={1} size="small" style={{ marginBottom: 12 }}>
                          <Descriptions.Item label="节点名称">
                            <Typography.Text strong>{selectedNode.label}</Typography.Text>
                          </Descriptions.Item>
                          <Descriptions.Item label="节点类型">
                            <Tag color={
                              selectedNode.type === 'source_table' ? 'blue' :
                              selectedNode.type === 'target_table' ? 'green' :
                              selectedNode.type === 'temp_table' ? 'orange' :
                              selectedNode.type === 'view' ? 'purple' : 'default'
                            }>
                              {selectedNode.type}
                            </Tag>
                          </Descriptions.Item>
                          {selectedNode.table_name && (
                            <Descriptions.Item label="表名">
                              {selectedNode.table_name}
                            </Descriptions.Item>
                          )}
                        </Descriptions>

                        {/* 字段信息 */}
                        {selectedNode.columns && selectedNode.columns.length > 0 && (
                          <>
                            <Divider style={{ margin: '12px 0' }} />
                            <div>
                              <Typography.Text strong style={{ fontSize: '14px' }}>
                                表字段 ({selectedNode.columns.length})
                              </Typography.Text>
                              <div style={{ marginTop: 8, maxHeight: 200, overflow: 'auto' }}>
                                {typeof selectedNode.columns[0] === 'object' ? (
                                  selectedNode.columns.map((column: any, index: number) => (
                                    <div key={index} style={{
                                      marginBottom: 8,
                                      padding: 8,
                                      border: `1px solid ${token.colorBorderSecondary}`,
                                      borderRadius: 4,
                                      backgroundColor: token.colorFillQuaternary
                                    }}>
                                      <div style={{ marginBottom: 4 }}>
                                        <Typography.Text strong style={{ color: token.colorPrimary }}>
                                          {column.name}
                                        </Typography.Text>
                                        <Tag size="small" style={{ marginLeft: 8 }}>
                                          {column.type}
                                        </Tag>
                                        {!column.nullable && (
                                          <Tag size="small" color="red" style={{ marginLeft: 4 }}>
                                            NOT NULL
                                          </Tag>
                                        )}
                                      </div>
                                      {column.comment && (
                                        <div style={{ fontSize: '12px', color: token.colorTextSecondary }}>
                                          💬 {column.comment}
                                        </div>
                                      )}
                                    </div>
                                  ))
                                ) : (
                                  selectedNode.columns.map((column: string, index: number) => (
                                    <Tag key={index} style={{ marginBottom: 4, display: 'block' }}>
                                      {column}
                                    </Tag>
                                  ))
                                )}
                              </div>
                            </div>
                          </>
                        )}

                        {/* WITH选项信息 */}
                        {selectedNode.with_options && Object.keys(selectedNode.with_options).length > 0 && (
                          <>
                            <Divider style={{ margin: '12px 0' }} />
                            <div>
                              <Typography.Text strong style={{ fontSize: '14px' }}>
                                连接器配置
                              </Typography.Text>
                              <div style={{
                                marginTop: 8,
                                padding: 8,
                                backgroundColor: token.colorSuccessBg || token.colorFillQuaternary,
                                border: `1px solid ${token.colorSuccessBorder || token.colorBorder}`,
                                borderRadius: 4,
                                maxHeight: 150,
                                overflow: 'auto'
                              }}>
                                {Object.entries(selectedNode.with_options).map(([key, value]) => (
                                  <div key={key} style={{ marginBottom: 4 }}>
                                    <Typography.Text style={{ fontSize: '12px' }}>
                                      <strong>{key}:</strong> {String(value)}
                                    </Typography.Text>
                                  </div>
                                ))}
                              </div>
                            </div>
                          </>
                        )}
                      </>
                    )}
                  </Card>
                </Col>
              )}
            </Row>

            <div style={{
              marginTop: '12px',
              padding: '12px',
              backgroundColor: token.colorInfoBg || token.colorFillQuaternary,
              borderRadius: '6px',
              border: `1px solid ${token.colorInfoBorder || token.colorBorder}`
            }}>
              <Typography.Text style={{ fontSize: '12px', color: token.colorTextSecondary }}>
                💡 <strong>使用提示</strong>: 单击任意节点可查看该节点的详细属性信息，包括字段、连接器配置等。点击空白区域或侧边栏关闭按钮可关闭详情面板。
              </Typography.Text>
            </div>
          </>
        )}
      </Modal>


    </>
  );
};

// 使用React.memo优化组件，只有props真正变化时才重新渲染
const HierarchicalLineageGraph = React.memo(HierarchicalLineageGraphComponent, arePropsEqual);

export default HierarchicalLineageGraph;
